<template>
  <view class="pt-5" v-if="!treeInfo">
    <q-load-icon />
  </view>
  <view class="pa-3" v-else>
    <view class="bdrs-8 ov-h">
      <q-item label="填写个人信息" clickable @click="$navTo('mine/info')">
        <q-item-todo :done="done1" />
      </q-item>
    </view>
    <view class="bdrs-8 ov-h mt-3">
      <q-item label="签订合同协议" clickable @click="onContract">
        <q-item-todo :done="done2" />
      </q-item>
    </view>

    <view class="pos-btm pos-f pa-3 bg-cell">
      <view>
        <u-button
          type="primary"
          :disabled="!allDone || isIn"
          :loading="paying"
          @click="onPay"
        >
          <span v-if="isIn">我已认养</span>
          <template v-else>
            <span>确认支付</span>
            <span class="fz-12">￥</span>
            <span>{{ treeInfo.price }}</span>
          </template>
        </u-button>
      </view>
      <u-safe-bottom />
    </view>
  </view>
</template>

<script>
import { mapState } from "vuex";

export default {
  computed: {
    ...mapState(["userInfo"]),
    userMeta() {
      return this.userInfo.user_metadata || this.userInfo;
    },
    done1() {
      const user = this.userMeta;
      return user.avatar_url && user.nickname;
    },
    allDone() {
      return this.done1 && this.done2;
    },
    isIn() {
      return this.userMeta.got_tree > 0;
    },
  },
  data() {
    return {
      treeInfo: null,
      done2: false,
      paying: false,
    };
  },
  created() {
    this.getInfo();
  },
  methods: {
    onContract() {
      this.$toast("dev");
      this.done2 = true;
    },
    async getInfo() {
      try {
        if (!this.isIn) {
          await this.$store.dispatch("getUserInfo");
        }
        this.treeInfo = await this.$store.dispatch("getTreeInfo");
      } catch (error) {
        console.log(error);
      }
    },
    async onPay() {
      try {
        let msg;
        if (!this.done1) {
          msg = "请填写个人信息";
        } else if (!this.done2) {
          msg = "请签署协议";
        }
        if (msg) {
          return this.$toast(msg);
        }
        this.paying = true;
        await this.$store.dispatch("payOrder", {
          buy_tree: 1,
        });
        this.$toast("认养成功", 1);
        await this.$sleep(1e3);
        this.$navBack();
      } catch (error) {
        console.log(error);
        uni.hideLoading();
      }
      this.paying = false;
    },
    async onBotPay() {
      const { data } = await uni.$api.get("/bot/test-pay");
    },
  },
};
</script>
